package com.rgs.gateway.web.common.config.bean;

import com.rgs.gateway.web.utils.IPAddressUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 自定义限流标志的key，多个维度可以从这里入手
 * exchange对象中获取服务ID、请求信息，用户信息等
 */
@Component
public class RequestRateLimiterConfig {
    //公共请求头变量名公钥
    private static final String APPKEY = "appKey";

    //易私慕请求头变量名公钥
    private static final String APPID = "appId";

    //华润请求头变量名公钥
    private static final String APPTOKEN = "appToken";


    /**
     * ip地址限流
     *
     * @return 限流key
     */
    @Bean
    @Primary
    public KeyResolver remoteAddressKeyResolver() {
        return exchange -> Mono.just(IPAddressUtils.getIpAddress(exchange.getRequest()));
    }

    /**
     * 请求路径限流
     *
     * @return 限流key
     */
    @Bean
    public KeyResolver apiKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * 请求头变量名公钥限流
     *
     * @return 限流key
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(StringUtils.isNotBlank(exchange.getRequest().getHeaders().getFirst(APPKEY)) ?
                exchange.getRequest().getHeaders().getFirst(APPKEY) : StringUtils.isNotBlank(exchange.getRequest().getHeaders().getFirst(APPID)) ?
                exchange.getRequest().getHeaders().getFirst(APPID) : StringUtils.isNotBlank(exchange.getRequest().getHeaders().getFirst(APPTOKEN)) ?
                exchange.getRequest().getHeaders().getFirst(APPTOKEN) : exchange.getRequest().getHeaders().getFirst(APPKEY));
    }
}
